package com.toolbox.dal.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.toolbox.dal.repository.InfraLogOperateDORepository;
import com.toolbox.dto.InfraLogOperateDTO;
import com.toolbox.dal.mapper.InfraLogOperateMapper;
import com.toolbox.dal.model.InfraLogOperateDO;
import com.toolbox.pages.Pager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Comparator;
import java.util.stream.Collectors;

import static com.toolbox.pages.PageUtil.convert;
import static com.toolbox.pages.PageUtil.defaultObjWhenEmpty;

/**
 * <p>
 * 操作日志表 服务实现类
 * </p>
 *
 * @author Mango
 * @since 2023-12-01
 */
@SuppressWarnings("ALL")
@Slf4j
@Service
public class InfraLogOperateDORepositoryImpl extends ServiceImpl<InfraLogOperateMapper, InfraLogOperateDO> implements InfraLogOperateDORepository {

    @Autowired
    private InfraLogOperateMapper mapper;

    @Override
    public Pager<InfraLogOperateDTO> getOperateLogPage(Integer pageIndex, Integer pageSize, String keywords) {
        QueryWrapper<InfraLogOperateDO> queryWrapper = new QueryWrapper<>();

        queryWrapper.lambda().orderByDesc(InfraLogOperateDO::getId);

        Page<InfraLogOperateDO> page = mapper.selectPage(new Page<InfraLogOperateDO>(pageIndex, pageSize), queryWrapper);

        if (page.getRecords().isEmpty()) {
            return defaultObjWhenEmpty();
        }

        return convert(page.getTotal(), page.getCurrent(), page.getSize(),
                page.getRecords().stream().map(this::doToDto).sorted(Comparator.comparing(InfraLogOperateDTO::getId)).collect(Collectors.toList()));
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void create(InfraLogOperateDO operationEntity) {
        mapper.insert(operationEntity);
    }

    /**
     * DO 转换 DTO
     *
     * @param dos
     * @return
     */
    private InfraLogOperateDTO doToDto(InfraLogOperateDO dos) {
        InfraLogOperateDTO dto = new InfraLogOperateDTO();
        BeanUtils.copyProperties(dos, dto);
        return dto;
    }

}
